﻿/**
 * ajax请求时加载状态
 */
Look.prototype.loader={
	show : function(){
		$(".loader").show();
		if($(".flim").length==0){
			$("body").append('<div class="flim"></div>');
		}
	},
	hide : function(){
		$(".loader").hide();
		$(".flim").remove();
	}
}

/**
 * 提示信息
 */
Look.prototype.showInfo = {
	showTimer : $.timer(function() {
		look.showInfo.hide();
	}),
	add : function(){
		if($(".info_panel").length==0){
			$("body").prepend('<div class="info_panel" id="infoPanel"><span></span></div>');
		}
	},
	hide : function(){
		this.showTimer.stop();
		this.add();
		$("#infoPanel").fadeOut();
	},
	right : function(text){
		this.add();
		this.showTimer.stop();
		this.showTimer.once(3000);
		$("#infoPanel").fadeIn().children("span").removeClass("errorInfo").html(text);
	},
	error : function(text){
		this.right(text);
		$("#infoPanel span").addClass("errorInfo");
	}
}

/**
 * 设置title
 * @param title
 * @return null
 */
Look.prototype.setTitle = function(title){
	document.title = title;
}

/**
 * 字符串查找
 * @param object 查找的字符
 * @param str 被查找的字符串
 * @return Boolean
 */
Look.prototype.hasString = function(object,str){
	var reg=eval("/"+object+"/gi");
	if(reg.test(str)){
		return true;
	}else{
		return false;
	}
}

/**
 * 过滤掉数组中重复的项
 * @param arr 需要过滤的数组
 * @return newArray 过滤后的数组
 */
Look.prototype.uniqueArray = function(arr){
	var newArray=[]; 
	var m; 
	while(arr.length>0){ 
		m=arr[0]; 
		newArray.push(m); 
		arr=$.grep(arr,function(n,i){
			return n==m; 
		},true); 
	} 
	return newArray;
}

/**
 * 对象或者数组的深层拷贝
 * 拷贝前后的对象相互不影响
 * @param destination
 * @param source
 * @return
 */
Look.prototype.copyArray = function(destination,source){
	function getType(o){
		var _t;
		return ((_t = typeof(o)) == "object" ? o==null && "null" || Object.prototype.toString.call(o).slice(8,-1):_t).toLowerCase();
	}
	for(var p in source){
		if(getType(source[p])=="array"||getType(source[p])=="object"){
            destination[p]=getType(source[p])=="array"?[]:{};
            arguments.callee(destination[p],source[p]);
        }else{
            destination[p]=source[p];
        }
    }
}

/**
 * 返回字符串在规定字节长度内的值  
 * @param val
 * @param max
 * @return String
 */
Look.prototype.getByteVal = function(val,max) {   
	var returnValue='';
	var byteValLen=0;
	var val=val.split("");
	for (var i=0;i<val.length;i++){
		if(val[i].match(/[^\x00-\xff]/ig)!=null){
			byteValLen+=2;
		}else {
			byteValLen+=1;
		}
		if (byteValLen>max){
			break;
		}
		returnValue+=val[i];
	}
	return returnValue;
}

/**
 * 返回字符串在规定字节长度内的值  
 * @param val
 * @param max
 * @return String
 */
Look.prototype.getByteVal = function(val,max) {   
	var returnValue='';
	var byteValLen=0;
	var val=val.split("");
	for (var i=0;i<val.length;i++){
		if(val[i].match(/[^\x00-\xff]/ig)!=null){
			byteValLen+=2;
		}else {
			byteValLen+=1;
		}
		if (byteValLen>max){
			break;
		}
		returnValue+=val[i];
	}
	return returnValue;
}

/**
 * 返回字符串的字节长度
 * @param val
 * @return int
 */
Look.prototype.getByteLen = function(val){   
	var len = 0,
		str = val.replace(" ","$"),
		charCode = -1;
    for (var i = 0; i < str.length; i++) {
    	charCode = str.charCodeAt(i);
    	if (charCode >= 0 && charCode <= 128) {
    		len += 1;
    	} else {
    		len += 2;
    	}
    }
    return len;
}

/**
 * 全文查找去除空格
 * @param str
 * @return 已去除空格的字符
 */
Look.prototype.trimAll = function(str){
	return str.replace(/(^\s+)|(\s+$)|( )/g, "");
}

/**
 * 全文空格验证
 * @param str
 * @return
 */
Look.prototype.verifyTrim = function(str){
	var trimReg = /(^\s+)|(\s+$)|( )/g;
	return trimReg.test(str);
}

/**
 * 生成id
 * @return
 */
Look.prototype.generateGuid = function(){
    var guid = "";
    for (var i = 1; i <= 32; i++){
          var n = Math.floor(Math.random()*16.0).toString(16);
          guid += n;
//        if((i==8)||(i==12)||(i==16)||(i==20))
//        	guid += "-";
    }
    return guid;
}

/**
 * 获取本地日期
 * @return 2012-06-02
 */
Look.prototype.getLocalDate = function(){
	var $date = new Date(),
		$y = $date.getFullYear(),
		$m = $date.getMonth()+1,
		$d = $date.getDate();
	if($m < 10){
		$m = "0" + $m;
	}
	if($d < 10){
		$d = "0" + $d;
	}
	return $y+"-"+$m+"-"+$d;
}

/**
 * 获得上个月在昨天这一天的日期
 * @param {Object} date
 */
Look.prototype.getLastMonthDate = function(date){
	var daysInMonth = new Array([0],[31],[28],[31],[30],[31],[30],[31],[31],[30],[31],[30],[31]),
		dateArray = date.split("-"),
		strYear = parseFloat(dateArray[0]),
		strDay = parseFloat(dateArray[2]),
		strMonth = parseFloat(dateArray[1]);
	if(strYear % 4 == 0 && strYear % 100 != 0){
		daysInMonth[2] = 29;
	}
	if(strMonth - 1 == 0){
		strYear -= 1;
		strMonth = 12;
	}else{
		strMonth -= 1;
	}  
		strDay = daysInMonth[strMonth] >= strDay ? strDay : daysInMonth[strMonth];
	if(strMonth < 10){    
		strMonth = "0" + strMonth;
	}
	if(strDay < 10){
		strDay="0" + strDay;
	}
	return strYear + "-" + strMonth + "-" + strDay;
}

/**
 * 指定日期增加天数
 * @param {Object} date
 * @param {Object} num
 */
Look.prototype.addDaysByDate = function(date, num){
	return new Date(Date.parse(date) + (86400000 * num));
}

/**
 * 日期格式化
 * "yyyy-MM-dd"
 * @param {Object} date
 * @param {Object} format
 */
Look.prototype.dateFormat = function(date, format){
	var o = {
		"M+" : date.getMonth()+1, //month
		"d+" : date.getDate(),    //day
		"h+" : date.getHours(),   //hour
		"m+" : date.getMinutes(), //minute
		"s+" : date.getSeconds(), //second
		"q+" : Math.floor((date.getMonth()+3)/3),  //quarter
		"S" : date.getMilliseconds() //millisecond
    }
    if (/(y+)/.test(format)) {
		format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
	}
    for (var k in o) {
		if (new RegExp("(" + k + ")").test(format)) {
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
		}
	}
    return format;
}

/**
 * 获取两个日期的间隔时间的天数（f是当前日期，s是之后的）
 * @param f 如：2012-06-02
 * @param s 如：2013-06-02
 * @return int
 */
Look.prototype.getDiffDays = function(f,s){
	var dateArray;
    var monthDays=[0,3,0,1,0,1,0,0,1,0,0,1];
    dateArray=f.split("-");
    var date1Year=dateArray[0];
    var date1Month=dateArray[1];
    var date1Day=dateArray[2];
    dateArray=s.split("-");
    var date2Year=dateArray[0];
    var date2Month=parseInt((dateArray[1]).replace(/\b(0+)/gi,""));
    var date2Day=parseInt((dateArray[2]).replace(/\b(0+)/gi,""));
	//判断年份是否是闰年 
    function isLeapYear(year) {  
        if(year % 4 == 0 && (year % 100 != 0) || (year % 400 == 0)){
        	return true;
        }
        return false;
	}
    
	//判断前后两个日期  
	function validatePeriod(fyear, fmonth, fday, byear, bmonth, bday){
		if(fyear < byear){
			return true;
		}else if(fyear == byear){
			if(fmonth < bmonth){
				return true;
			}else if(fmonth == bmonth){
				if(fday <= bday){
					return true;
				}else{
					return false;
				}
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
    if(validatePeriod(date1Year,date1Month,date1Day,date2Year,date2Month,date2Day)){
        var firstDate = new Date(date1Year, date1Month, date1Day);
        var secondDate = new Date(date2Year, date2Month, date2Day);
        var result = Math.floor((secondDate.getTime() - firstDate.getTime()) / (1000*3600*24));
        for(j = date1Year; j < date2Year; j++){
            if(isLeapYear(j)){
                monthDays[1] = 2;
            }else{
                monthDays[1] = 3;
            }
            for(i = date1Month -1 ; i < date2Month; i++){
                result = result - monthDays[i];
            }
        }
        return result;
    }else{
        return ;
    }
}

/**
 * 获取指定的URL参数值 
 * @param {String} paramName URL参数
 * @param {String} from 来源
 * @return paramValue URL参数值
 */
Look.prototype.getParam = function(paramName) {
	var paramValue = "";
	var isFound = false;
	if (location.search.indexOf("?") == 0 && location.search.indexOf("=") > 1) {
		var arrSource = unescape(location.search).substring(1,location.search.length).split("&");
		i = 0;
		while (i < arrSource.length && !isFound) {
			if (arrSource[i].indexOf("=") > 0) {
				if (arrSource[i].split("=")[0].toLowerCase() == paramName.toLowerCase()) {
					paramValue = arrSource[i].split("=")[1];
					isFound = true;
				}
			}
			i++;
		}
	}
	return paramValue;
}

/**
 * 重新设置参数值
 * @param {Array} key 如：[["aa","11"],["bb","22"]]
 * @param {String} source
 * @return
 */
Look.prototype.setParam = function(key, source){
	var theNewStr = source;
	function single(keyStr, sourceStr){
		var arr = sourceStr.split("&"),
			newArr = "";
		for (var i = 0; i < arr.length; i++){
			if (arr[i].split("=")[0] == keyStr[0]) {
				newArr += keyStr[0] + "=" + keyStr[1] + "&";
			}else{
				newArr += arr[i].split("=")[0] + "=" + arr[i].split("=")[1] + "&";
			}
		}
		return newArr.replace(/[&]$/, "");
	}
	for(var j = 0; j < key.length; j++){
		theNewStr = single(key[j], theNewStr);
	}
	return theNewStr.replace(/[&]$/, "");
}

/**
 * 获取指定的URL中的hash参数值 
 * @param {String} paramName URL参数
 * @return paramValue URL参数值
 */
Look.prototype.getHashParam = function(paramName) {
	var paramValue = "";
	var isFound = false;
	if (location.hash.indexOf("#") == 0 && location.hash.indexOf("=") > 1) {
		var arrSource = unescape(location.hash).substring(1,location.hash.length).split("&");
		i = 0;
		while (i < arrSource.length && !isFound) {
			if (arrSource[i].indexOf("=") > 0) {
				if (arrSource[i].split("=")[0].toLowerCase() == paramName.toLowerCase()) {
					paramValue = arrSource[i].split("=")[1];
					isFound = true;
				}
			}
			i++;
		}
	}
	return paramValue;
}

/**
 * 获取指定的cookie中的参数值
 * @param key
 * @param source
 * @return
 */
Look.prototype.getCookieParam = function(key,source){
	if($.cookie(source)){
		var arr = $.cookie(source).split("&");
		for (var i=0; i<arr.length; i++){
			if(arr[i].split("=")[0] == key){
				return arr[i].split("=")[1];
			}
		}
	}
}

/**
 * 获取String中的参数值
 * @param key
 * @param source
 * @return
 */
Look.prototype.getStringParam = function(key,source){
	if (source.indexOf("#") != -1 || source.indexOf("?") != -1) {
		source = source.substr(1);
	}
	var arr = source.split("&");
	for (var i=0; i<arr.length; i++){
		if(arr[i].split("=")[0] == key){
			return arr[i].split("=")[1];
		}
	}
}

/**
 * 重新设置参数值
 * @param {Array} key 如：[["aa","11"],["bb","22"]]
 * @param {String} source
 * @return
 */
Look.prototype.setParam = function(key, source){
	var theNewStr = source;
	function single(keyStr, sourceStr){
		var arr = sourceStr.split("&"),
			newArr = "";
		for (var i = 0; i < arr.length; i++){
			if (arr[i].split("=")[0] == keyStr[0]) {
				newArr += keyStr[0] + "=" + keyStr[1] + "&";
			}else{
				newArr += arr[i].split("=")[0] + "=" + arr[i].split("=")[1] + "&";
			}
		}
		return newArr.replace(/[&]$/, "");
	}
	for(var j = 0; j < key.length; j++){
		theNewStr = single(key[j], theNewStr);
	}
	return theNewStr.replace(/[&]$/, "");
}

/**
 * 数据请求方法
 * @param requestData
 * @param httpHeader
 * @param responseFn
 * @return
 */
function dataConn(url,requestData,responseFn){
	$.ajax({
		type : "POST",
		url : url,
		dataType : "json",
		data : requestData,
		timeout : 15000,
		beforeSend : function(XMLHttpRequest){
		},
		success : function(back,textStatus,XMLHttpRequest){
			if(back.code == "302"){
				look.showInfo.error(back.code + "：非法登录，正在为您跳转……");
				location.href = back.message;
				return false;
			}
			if(back != null){
				if(back.code == "5001"){
					look.showInfo.error(back.code + "：" +back.message);
					return false;
				}
				if(responseFn != undefined){
					try {
						eval(responseFn(back,textStatus));
					} catch (e) {
						look.showInfo.error("[ERROR] name: " + e.name + "message: " + e.message);
					}
				}
			}else{
				look.showInfo.error("网络连接出错！");
			}
		},
		error : function(XMLHttpRequest, error){
			if(error == "timeout"){
				look.showInfo.error("请求超时：请求系统返回数据超时！请稍候再试吧……");
			}else{
				look.showInfo.error(error + "：请求出错！请稍后再试吧……");
			}
		},
		complete : function(XMLHttpRequest, textStatus){
		}
	});
}

/**
 * 同步加载页面
 * @param {String} container 页面存放的div容器
 * @param {String} url 加载的页面URL
 * @param {String} callback 回调函数
 */
function loadPage(container,url,callback) {
	$.ajax({
		url : url,
		async : false,
		success : function(html) {
			$(container).html(html);
		},
		complete : function() {
			if(callback!=undefined){
				eval(callback);
			}
		},
		error : function(XmlHttpRequest, textStatus, errorThrown) {
			popError("<div style='width:480px;'>加载页面出错，请进行<a href='javascript:window.location.reload();'>刷新</a>，然后再试一次。</div>");
		}
	});
}

/**
 * 分页
 * @param id 插入页码的地方
 * @param pageSize 每页数目
 * @param hashArray hash数组值
 * @param count 总数
 * @return
 */
function setPager(id,pageSize,hashArray,count){
	var theHtml="",className="";
	if(count==0 || count==undefined){
		$(id).html(theHtml);
		return false;
	}
	var currentPager=1,pageStep=5,pageCount,beginPage,endPage;
	//分页算法
	pageCount=Math.ceil(count/pageSize);
	currentPager=parseInt(hashArray[1] ? hashArray[1] : 1);
	if(pageCount<currentPager){currentPager=pageCount;}
	if(currentPager<1){currentPager=1;}
	beginPage=(currentPager-Math.ceil(pageStep/2));
	if(beginPage<1){beginPage=1;}
	endPage=currentPager+pageStep/2;
	if(endPage>pageCount){endPage=pageCount+1;}
	
	if(currentPager==1){
		theHtml+='<a href="javascript:" class="disabled">首页</a>';
		theHtml+='<a href="javascript:" class="disabled">上一页</a>';
	}else{
		theHtml+='<a href="'+hashArray[0]+'">首页</a>';
		if(currentPager==2){
			theHtml+='<a href="'+hashArray[0]+'">上一页</a>';
		}else{
			theHtml+='<a href="'+hashArray[0]+"&page="+(currentPager-1)+'">上一页</a>';
		}
	}
	for(var i=beginPage;i<endPage;i++){
		if(currentPager==i){
			className="selected";
		}else{
			className="";
		}
		if(i==1){
			theHtml+='<a href="'+hashArray[0]+'" class="'+className+'">'+(i)+'</a>';
		}else{
			theHtml+='<a href="'+hashArray[0]+"&page="+i+'" class="'+className+'">'+(i)+'</a>';
		}
	}
	if(currentPager==pageCount){
		theHtml+='<a href="javascript:" class="disabled">下一页</a>';
		theHtml+='<a href="javascript:" class="disabled">末页</a>';
	}else{
		theHtml+='<a href="'+hashArray[0]+"&page="+(currentPager+1)+'">下一页</a>';
		theHtml+='<a href="'+hashArray[0]+"&page="+pageCount+'">末页</a>';
	}
	theHtml+='<span class="pager_total">共<span id="pagerTotal">'+pageCount+'</span>页</span><span class="goto_pager">到</span><input type="text" class="text" id="gotoPage" /><span class="goto_pager">页</span><a href="javascript:" id="gotoSubset" class="a_as_button">确定</a>';
	$(id).html(theHtml);
	$("#gotoPage").bind("blur",function(){
		var i=$(this).val();
		if(isNaN(i)||i<=0){i=1;}
		if(i>pageCount){i=pageCount;}
		if(i!=""){
			if(i==1){
				$("#gotoSubset").attr("href",hashArray[0]);
			}else{
				$("#gotoSubset").attr("href",hashArray[0]+"&page="+i);
			}
		}
	});
}